package com.example.musicbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.musicbox.config.MyException;
import com.example.musicbox.entity.MCatalogue;
import com.example.musicbox.entity.MMusic;
import com.example.musicbox.entity.MUserCatalogue;
import com.example.musicbox.enums.AboutMusic;
import com.example.musicbox.enums.LogDoType;
import com.example.musicbox.mapper.MCatalogueMapper;
import com.example.musicbox.mapper.MMusicMapper;
import com.example.musicbox.mapper.MUserCatalogueMapper;
import com.example.musicbox.service.MCatalogueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.musicbox.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 帅哥是我
 * @since 2022-08-01
 */
@Service
public class MCatalogueServiceImpl extends ServiceImpl<MCatalogueMapper, MCatalogue> implements MCatalogueService {

    @Resource
    private MLogServiceImpl mLogService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private MCatalogueMapper mCatalogueMapper;

    @Resource
    private MUserCatalogueMapper mUserCatalogueMapper;

    @Resource
    private MMusicMapper mMusicMapper;

    private static final Logger LOGGER= LoggerFactory.getLogger(MCatalogueServiceImpl.class);


    /**
     * 添加目录
     * @param mCatalogue
     * @return
     */
    @Override
    public Result addMCatalogue(MCatalogue mCatalogue,String token) {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            mCatalogue.setUid(userId);
            mCatalogue.setCSort(10);
            mCatalogueMapper.insert(mCatalogue);
            mLogService.insertLog("用户新增目录",AboutMusic.NOTHINGABOUTMUSIC,null, LogDoType.INSERT,token);
        }catch (Exception e){
            LOGGER.error("添加目录失败");
            throw new MyException("添加目录失败");
        }
        return Result.ok("目录添加成功");
    }


    /**
     * 更改目录信息
     * @param mCatalogue
     * @return
     */
    @Override
    public Result updateMCatalogue(MCatalogue mCatalogue,String token) {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            //自己只可以修改自己的目录
            if(mCatalogue.getUid().equals(userId)) {
                QueryWrapper<MCatalogue> wrapper = new QueryWrapper<>();
                wrapper.eq("mId",mCatalogue.getMid());
                mCatalogueMapper.update(mCatalogue,wrapper);
                mLogService.insertLog("用户修改目录",null,null, LogDoType.UPDATE,token);
                return Result.ok("目录修改成功");
            }else {
                return Result.error("没有权限修改");
            }
        }catch (Exception e) {
            throw new MyException("目录修改失败");
        }
    }


    /**
     * 删除目录信息
     * @param
     * @return
     */
    @Override
    public Result deleteMCatalogue(String token, Integer id) {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            MCatalogue mCatalogue = mCatalogueMapper.selectById(id);
            if (mCatalogue.getMid().equals(userId)) {
                //当用户删除目录的时候，同时也把该目录下的音乐列表给删除掉
                QueryWrapper<MUserCatalogue> wrapper = new QueryWrapper<>();
                wrapper.eq("cId", id);
                List<MUserCatalogue> mUserCatalogues = mUserCatalogueMapper.selectList(wrapper);
                List<Integer> list = mUserCatalogues.stream().map(MUserCatalogue::getMid).collect(Collectors.toList());
                //删除目录列表中的内容
                mUserCatalogueMapper.deleteListByMusicIds(list);
                //删除目录
                mCatalogueMapper.deleteById(id);
                //日志记录
                mLogService.insertLog("用户删除目录", AboutMusic.NOTHINGABOUTMUSIC, null, LogDoType.DELETE, token);
                return Result.ok("目录删除成功");
            } else {
                return Result.ok("没有删除权限");
            }
        } catch (Exception e) {
            throw new MyException("目录删除失败");
        }
    }


    /**
     * 根据token查询用户目录信息
     * @param
     * @return
     */
    @Override
    public Result selectMCatalogue(String token) {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            QueryWrapper<MCatalogue> wrapper = new QueryWrapper<>();
            wrapper.eq("uId", userId);
            List<MCatalogue> mCatalogueList = mCatalogueMapper.selectList(wrapper);
            for (MCatalogue catalogue : mCatalogueList) {
                QueryWrapper<MUserCatalogue> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("cId", catalogue.getMid());
                List<MUserCatalogue> mUserCatalogueList = mUserCatalogueMapper.selectList(queryWrapper);
                List<Integer> list = mUserCatalogueList.stream().map(MUserCatalogue::getMid).collect(Collectors.toList());
                List<MMusic> mMusics = mMusicMapper.selectMusicList(list);
                catalogue.setMusicList(mMusics);
            }
            return Result.ok("用户目录信息查询成功").put("mCatalogueList", mCatalogueList);
        } catch (Exception e) {
            throw new MyException("用户目录列表信息查询失败");
        }
    }


    /**
     * 查询用户的列表信息(这里我想直接在用户添加音乐的时候选择用户的目录选项)
     * @param token
     * @return
     */
    @Override
    public Result selectSimpleMCatalogue(String token) {
        try {
            Integer userId = (Integer) redisTemplate.opsForValue().get(token);
            QueryWrapper<MCatalogue> wrapper = new QueryWrapper<>();
            wrapper.eq("uId", userId);
            List<MCatalogue> mCatalogues = mCatalogueMapper.selectList(wrapper);
            return Result.ok("用户目录列表查询成功").put("mCatalogues", mCatalogues);
        } catch (Exception e) {
            throw new MyException("用户目录列表查询失败");
        }
    }
}
